package com.yh.jandan.ext.thread;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.alibaba.druid.filter.stat.StatFilter;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.yh.jandan.model.Config;
import com.yh.jandan.model.Meizi;
import com.yh.jandan.util.DateUtils;

public class WatchThread {
	// static Timer timer = null ;
	
	private final static String _CONFIG_ = getD ( "config" , "a_little_config.txt" );
	
	public static void main ( String [ ] args ) {
		init ( );
		start ( );
		stop ( );
	}
	
	static DruidPlugin dp;
	static ActiveRecordPlugin arp;
	
	private static void init ( ) {
		Prop p = PropKit.use ( new File ( _CONFIG_ ) );
		dp = new DruidPlugin ( p.get ( "jdbcUrl" ).trim ( ) , p.get ( "user" ) , p.get ( "password" ) );
		dp.addFilter ( new StatFilter ( ) );
		dp.setMinIdle ( 5 )//
				.setTimeBetweenEvictionRunsMillis ( 6 * 1000 )//
				.setValidationQuery ( "select 1" )//
				.setTestWhileIdle ( true )//
				.setTestOnBorrow ( true )//
				.setTestOnReturn ( true ); //
		dp.start ( );
		arp = new ActiveRecordPlugin ( dp );
		arp.setDialect ( new MysqlDialect ( ) );
		arp.addMapping ( "config" , "id" , Config.class );
		arp.addMapping ( "meizi" , "id" , Meizi.class );
		
		arp.start ( );
	}
	
	private static void stop ( ) {
		// if ( null != timer ) timer.cancel ( ) ;
		// timer = null ;
		arp.stop ( );
		dp.stop ( );
	}
	
	private static void start ( ) {
		// System.out.println("start" ) ;
		// if ( "".equals ( "" ) ) return;
		// if ( null != timer ) timer.cancel ( ) ;
		// timer = new Timer ( ) ;
		// timer.schedule ( new TimerTask ( ) {
		// public void run ( ) {
		try {
			write_log ( "udpate_js_file():[" + new Date ( ) + "]" );
			udpate_js_file ( );
		} catch ( Exception e ) {
			e.printStackTrace ( );
		}
		// }
		// } , new Date ( new Date ( ).getTime ( ) + 1 * 1000 ) , 2 * 60 * 1000
		// ) ;
	}
	
	protected static void udpate_js_file ( ) {
		// Date min_day = get_min_day ( ) , now = new Date ( ) ;
		Date min_day = DateUtils.addDay ( new Date ( ) , -1 * ( Integer.valueOf ( getD ( "minday" , 10 + "" ) ) ) ) , now = new Date ( );
		if ( null == min_day ) throw new RuntimeException ( "udpate_js_file" );
		Date tmp_day = min_day;
		while ( tmp_day.getTime ( ) <= now.getTime ( ) ) {
			File file = get_date_file ( tmp_day );
			if ( !file.exists ( ) ) gen_js_file ( tmp_day , file );
			else {
				if ( DateUtils.addDay ( tmp_day , Integer.valueOf ( getD ( "modifyday" , 2 + "" ) ) ).getTime ( ) >= now.getTime ( ) ) gen_js_file ( tmp_day , file );
			}
			tmp_day = DateUtils.addDay ( tmp_day , 1 );
		}
		
	}
	
	private static void gen_js_file ( Date tmp_day , File js_file ) {
		String jstpl = "var day{day}={json};";
		String sql = "select website ,`show`, count(`md5`) count";
		sql += " from meizi";
		// sql += " where  substr(createdate,0,11)=?";
		sql += " where  DATE_FORMAT(createdate , '%Y-%m-%d')=?";
		sql += " group by  website ,`show`";
		sql += " order by  website ,`show` desc";
		System.out.println ( "["+tmp_day+"]"+sql );
		List < Record > rds = Db.find ( sql , DateUtils.getDateByFormat ( tmp_day , DateUtils.getFormat ( "-" ) ) );
		if ( null == rds || rds.size ( ) < 1 ) return;
		String jsstr = jstpl//
				.replace ( "{day}" , DateUtils.getDateByFormat ( tmp_day , DateUtils.getFormat ( "" ) ) )//
				.replace ( "{json}" , JsonKit.toJson ( rds ) );
		write_file ( js_file , jsstr );
	}
	
	private static void write_file ( File js_file , String jsstr ) {
		try {
			FileUtils.write ( js_file , jsstr , false );
		} catch ( IOException e ) {
			e.printStackTrace ( );
		}
	}
	
	public static File get_date_file ( Date tmp_day ) {
		String daystr = DateUtils.getDateByFormat ( tmp_day , DateUtils.getFormat ( "" ) );
		return new File ( getD ( "web" , PathKit.getRootClassPath ( ) + File.separator + "watch" ) , daystr + ".js" );
	}
	
	private static Date get_min_day ( ) {
		// String sql = "select min(substr(createdate,0,11)) from meizi";
		String sql = "select DATE_FORMAT(min(createdate), '%Y-%m-%d') from meizi";
		System.out.println ( sql );
		String date = Db.queryStr ( sql );
		return DateUtils.getDateByStrToYMD ( date );
	}
	
	private static void write_log ( String string ) {
		try {
			System.out.println ( string );
			FileUtils.write ( new File ( getLogFile ( ) ) , string + "\r\n" , true );
		} catch ( IOException e ) {
			e.printStackTrace ( );
		}
	}
	
	private static String getLogFile ( ) {
		String datestr = DateUtils.getDateByFormat ( DateUtils.YMD_FORMAT );
		String log_file = getD ( "log" , "WatchThread-{date}.log" );
		return log_file.replace ( "{date}" , datestr );
	}
	
	private static String getD ( String k , String d ) {
		String v = System.getProperty ( k );
		boolean b = null == v || "".equals ( v );
		return b ? d : v;
	}
	
}
